import numpy as np
import matplotlib.pyplot as plt

def low_pass_filter(signal, cutoff, sample_rate):
    # 进行傅里叶变换
    fft_signal = np.fft.fft(signal)
    frequencies = np.fft.fftfreq(len(signal), 1/sample_rate)

    # 创建掩码
    mask = np.abs(frequencies) <= cutoff

    # 应用掩码
    filtered_fft = fft_signal * mask

    # 进行逆傅里叶变换
    filtered_signal = np.fft.ifft(filtered_fft)

    return np.real(filtered_signal)

if __name__ == "__main__":
    # 生成示例时间序列信号
    sample_rate = 1000  # 采样率
    t = np.linspace(0, 1, sample_rate, endpoint=False)
    signal = np.sin(2 * np.pi * 50 * t) + np.sin(2 * np.pi * 120 * t)  # 包含 50Hz 和 120Hz 的信号

    # 应用低通滤波器
    cutoff = 100  # 截止频率
    filtered_signal = low_pass_filter(signal, cutoff, sample_rate)

    # 显示结果
    plt.figure(figsize=(12, 6))
    plt.subplot(2, 1, 1)
    plt.plot(t, signal)
    plt.title('Original Signal')
    plt.subplot(2, 1, 2)
    plt.plot(t, filtered_signal)
    plt.title('Filtered Signal')
    plt.tight_layout()
    plt.show()